import { getRequest } from '@/utils/api'

/**
 * 初始化路由
 * @param router
 * @param store
 * @param first
 */
export const initMenu = (router, store) => {
  return new Promise((resolve, reject) => {
    if (store.state.routes.length > 0) {//有数据就不查询了直接返回
      resolve(true)
      return
    }
    getRequest('/system/cfg/menu')
      .then(data => {
        if (data) {
          // 获取格式化后的路由
          let fmtRoutes = formatRoutes(data)
          // 添加到router中
        
          fmtRoutes.forEach(route => {
           //一个一个放入路由中，这里需要注意的是路由的path属性不能重复，否则在访问相应的路径时会没有反应
            router.addRoute(route)
          })
          // 将数据存入store
          store.commit('initRoutes', fmtRoutes)
          resolve(true)
        }
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * 格式化路由
 * @param routes
 * @returns {*[]}
 */
const formatRoutes = routes => {
  let fmtRoutes = []
  routes.forEach(router => {
    let { path, component, name, iconCls, children } = router
    let comp = null
    if (children && children instanceof Array) {
      children = formatRoutes(children)
    }
    console.info('===================',component);
    if (component === 'Home') {
      comp = () => import('@/views/Home')
    } else if (component === 'Login') {
      comp = () => import('@/views/Login')
    }else {
  console.info('===================');
    console.info('======',component);
      if(component){
        comp = () =>
        import(
          '@/views/' +
            component
              .toString()
              .toLowerCase()
              .substring(0, 3) +
            '/' +
            component
        )
      }else{
         comp = () => import('@/views/Login')
      }
        
      
      
    }
    let fmtRouter = {
      path: path,
      name: name,
      iconCls: iconCls,
      children: children,
      component: comp
    }
    fmtRoutes.push(fmtRouter)
  })
  return fmtRoutes
}
